﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EquipSecs300;

namespace EquipSecs300
{
    public class SysTimeHelper
    {
        //api函数声明   
        [DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
        public extern static bool SetSystemTime(ref SYSTEMTIME time);
        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME
        {
            public short Year;
            public short Month;
            public short DayOfWeek;
            public short Day;
            public short Hour;
            public short Minute;
            public short Second;
            public short Miliseconds;
        }

        public SysTimeHelper()
        {
            Microsoft.Win32.SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged);
        }

        private void SystemEvents_TimeChanged(object sender, EventArgs e)
        {
            MessageBox.Show("系统日期修改成功！", "提示", MessageBoxButtons.OK);
        }

        int mYear;
        int mDay;
        int mMonth;
        public void SetSysTime(DateTime dataTime)
        {
            //DialogResult res = MessageBox.Show($"是否将系统时间修改为: {dataTime.ToString()}!", "提示", MessageBoxButtons.OK);
            
            mYear = dataTime.Year;
            mMonth = dataTime.Month;
            mDay = dataTime.Day;
            //调用代码   
            SYSTEMTIME t = new SYSTEMTIME();
            t.Year = (short)mYear;
            t.Month = (short)mMonth;
            t.Day = (short)mDay;
            t.Hour = (short)(dataTime.Hour - 8);//这个函数使用的是0时区的时间,例如，要设12点，则为12-8   
            t.Minute = (short)dataTime.Minute;
            t.Second = (short)dataTime.Second;
            bool v = SetSystemTime(ref t);
        }
    }

}
